package com.iwith.dongmoon.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.iwith.dongmoon.gsonlist.PictureList;
import com.iwith.dongmoon.gsonlist.PictureListItem;
import com.iwith.dongmoon.listadpater.PhotoGridAdapter;
import com.iwith.dongmoon.util.ApiCode;
import com.iwith.dongmoon.util.HttpRequestor;
import com.iwith.dongmoon.util.ImageDownloader;
import com.iwith.dongmoon.util.ImageDownloader.Mode;
import com.iwith.dongmoon.util.RequestGson;
import com.iwith.dongmoon.util.ResultCode;
import com.iwith.dongmoon.util.ThreadInterface;
import com.iwith.dongmoon.util.ThreadTask;

public class PhotosActivity extends Activity implements OnClickListener {
	public static final int REQUEST_GALLERY = 1;
	public static final int REQUEST_CAMERA = 0;

	private GridView photoGridView;
	private TextView prevButton;
	private Button uploadButton;
	private ImageView title;

	private String userid;
	private String code;

	private AlertDialog.Builder mAlertDialog;
	private ImageDownloader mImageDownloader;;

	private RequestGson requestGson = new RequestGson();
	private Context mContext;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photos);
	}

	@Override
	public void onResume() {
		super.onResume();
		Initialize();
	}

	private void Initialize() {
		mContext = this;
		userid = getIntent().getExtras().getString("userid");
		code = getIntent().getExtras().getString("code");

		title = (ImageView) findViewById(R.id.title);
		photoGridView = (GridView) findViewById(R.id.photos_gridview);
		uploadButton = (Button) findViewById(R.id.photos_uploadBt);
		prevButton = (TextView) findViewById(R.id.backbtn);
		
		mImageDownloader = new ImageDownloader();
		mImageDownloader.setMode(Mode.CORRECT);
		mAlertDialog = new AlertDialog.Builder(this);

		setData(userid, code, photoGridView);

		if (code.equals(ApiCode.USERPHOTO) == true	|| code.equals(ApiCode.BIZPHOTO) == true) {
			uploadButton.setVisibility(View.GONE);
		} else if (code.equals(ApiCode.MODIFYUSERPHOTO) == true || code.equals(ApiCode.MODIFYBIZPHOTO) == true) {
			uploadButton.setVisibility(View.VISIBLE);
			uploadButton.setOnClickListener(this);
		}

		prevButton.setOnClickListener(this);
		title.setOnClickListener(this);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK)
			return;

		if (requestCode == REQUEST_GALLERY) {
			Uri imageUri = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(imageUri,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String filePath = cursor.getString(columnIndex);
			cursor.close();

			Bitmap bitmap = BitmapFactory.decodeFile(filePath);// , option);

			// 이미지 생성
			File imageFile = new File(filePath);

			// 썸네일 생성
			Bitmap thumbnail = Bitmap.createScaledBitmap(bitmap, 80, 80, true);

			File path = null;
			String state = Environment.getExternalStorageState();
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				path = Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
			} else {
				path = getFilesDir();
			}
			if (!path.exists())
				path.mkdirs();

			File thumbnailFile = new File(path, "iwith_thumbnail_"
					+ userid + ".jpg");

			FileOutputStream out = null;
			try {
				out = new FileOutputStream(thumbnailFile.getPath());
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (out != null) {
				thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, out);
			}

			uploadPicture(imageFile, thumbnailFile);

		} else if (requestCode == REQUEST_CAMERA) {

			// intent 의 여분 데이터로 저장된 비트맵 이미지를 얻는다. Bitmap bitmap = (Bitmap)
			Bitmap bitmap = (Bitmap) data.getExtras().get("data");
			Bitmap thumbnail = Bitmap.createScaledBitmap(bitmap, 80, 80, true);

			File path = null;
			String state = Environment.getExternalStorageState();
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				path = Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
			} else {
				path = getFilesDir();
			}
			if (!path.exists())
				path.mkdirs();

			File imageFile = new File(path, "iwith_image_" + userid
					+ ".jpg");
			File thumbnailFile = new File(path, "iwith_thumbnail_"
					+ userid + ".jpg");

			FileOutputStream imageOut = null;
			FileOutputStream thumbnailOut = null;
			try {
				imageOut = new FileOutputStream(imageFile.getPath());
				thumbnailOut = new FileOutputStream(thumbnailFile.getPath());
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (imageOut != null && thumbnailOut != null) {
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, imageOut);
				thumbnail.compress(Bitmap.CompressFormat.JPEG, 100,
						thumbnailOut);
			}

			uploadPicture(imageFile, thumbnailFile);
		}
	}

	private void uploadPicture(File image, File thumbnailImage) {
		HttpRequestor requestor = null;
		try {
			String api = null;
			if (code.equals(ApiCode.MODIFYUSERPHOTO) == true) {
				api = ApiCode.API_UPLOADPICTURE;
			} else if (code.equals(ApiCode.MODIFYBIZPHOTO) == true) {
				api = ApiCode.API_UPLOADBIZPICTURE;
			}

			requestor = new HttpRequestor(new URL(getString(R.string.api_url)
					+ api));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		if (requestor != null && image != null && thumbnailImage != null) {
			requestor.addParameter("userid", userid);
			requestor.addFile("thumbnail", thumbnailImage);
			requestor.addFile("picture", image);

			try {
				System.out.println("--이미지 전송 결과--");
				InputStream is = requestor.sendMultipartPost(this);
				BufferedReader bin = new BufferedReader(new InputStreamReader(
						is));
				String line = null;
				while ((line = bin.readLine()) != null) {
					System.out.println(line);
				}
				System.out.println("--이미지 전송 결과--");
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
			}
		}
	}

	private void setData(final String userid,
			final String code, final GridView gridView) {
		ThreadInterface threadInterface = new ThreadInterface() {
			PictureList pictureList;

			public void onThread() {
				// TODO Auto-generated method stub
				String api = null;
				if (code.equals(ApiCode.USERPHOTO) == true || code.equals(ApiCode.MODIFYUSERPHOTO) == true) {
					api = ApiCode.API_PICTURELIST;
				} else if (code.equals(ApiCode.BIZPHOTO) == true || code.equals(ApiCode.MODIFYBIZPHOTO) == true) {
					api = ApiCode.API_BIZPICTURELIST;
				}

				pictureList = requestGson.getPictureGsonBySendingAPI(mContext, api, "GET", "/" + userid);
			}

			public void onThreadEnd() {
				if (pictureList.getResultCode().equals(ResultCode.SUCCESS) == true) {
					PhotoGridAdapter adapter = new PhotoGridAdapter(mContext, R.layout.griditem_photo,	(ArrayList<PictureListItem>) pictureList.getList(), code);
					gridView.setAdapter(adapter);
				} else {
					requestGson.alertToast(mContext, code+" 데이터 로딩 실패");
				}
			}

		};
		ThreadTask task = new ThreadTask((Activity) mContext, threadInterface);
		task.execute();
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId()==uploadButton.getId()){
			final String items[] = { "앨범에서 불러오기", "찍어서 올리기", "취소" };
			mAlertDialog.setTitle("사진등록하기");
			mAlertDialog.setSingleChoiceItems(items, 0,	new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					Intent intent = null;
					switch (whichButton) {
					case 0:
						intent = new Intent(Intent.ACTION_PICK);
						intent.setType("image/*");
						startActivityForResult(intent, REQUEST_GALLERY);
						break;

					case 1:
						intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						startActivityForResult(intent, REQUEST_CAMERA);
						break;
					}
					dialog.dismiss();
				}
			});
			mAlertDialog.show();
		} else if(v.getId()==prevButton.getId()){
			finish();
		} else if(v.getId()==title.getId()){
			Intent intent=new Intent(this, MainIconView.class);
			intent.putExtra("flag", true);
			startActivity(intent);
		}
	}
}
